package com.saumya.robotlegs.controller
{
	import com.saumya.robotlegs.events.JSFLCreationEvent;
	import com.saumya.robotlegs.events.LoggerEvent;
	import com.saumya.robotlegs.model.JsflModel;
	import com.saumya.robotlegs.model.SearchedFilesModel;
	import com.saumya.utils.ArrayUtil;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import mx.logging.LogEvent;
	
	import nl.demonsters.debugger.MonsterDebugger;
	
	import org.robotlegs.mvcs.Command;

	public class CreateBatchFilesCommand extends Command
	{
		[Inject]
		public var jsflEvent:JSFLCreationEvent;
		
		[Inject]
		public var searcheFilesModel:SearchedFilesModel;
		
		[Inject]
		public var jsflModel:JsflModel;
		
		private var arrayOfSets:Array=[];
		private var numJSFLCreated:uint=0;
		
		public function CreateBatchFilesCommand()
		{
			//Empty Constructor
		}
		
		public override function execute():void
		{
			MonsterDebugger.trace(this,'CreateBatchFilesCommand : masterBatchFiles='+File(this.jsflModel.getMasterScriptFile()).nativePath);
			MonsterDebugger.trace(this,'CreateBatchFilesCommand : numFiles in batch='+this.jsflEvent.getNumFilesInBatch());
			this.createBatchJsflFiles();
		}
		
		private function createBatchJsflFiles():void
		{
			this.makeTheScriptForBatchPublish();
		}
		
		private function makeTheScriptForBatchPublish():void
		{
			var numFilesInBatch:uint=this.jsflEvent.getNumFilesInBatch();
			var totalFiles:Array=this.searcheFilesModel.getAllFiles();
			//
			var fInt:uint = numFilesInBatch;
			//
			var au:ArrayUtil = new ArrayUtil();
			this.arrayOfSets = [];
			this.arrayOfSets = au.makeSet(totalFiles.length, fInt);
			//
			this.createBatchJSFL();
		}
		
		private function createBatchJSFL():void
		{
			var setArrayBundle:Array = [];
			setArrayBundle = this.arrayOfSets;
			//
			for ( var i:uint = 0; i < setArrayBundle.length;i++ )
			{
				if (this.numJSFLCreated==i)
				{	
					var oneSet:Array = setArrayBundle[i];
					var desktop:File = new File();
					desktop = File.desktopDirectory;
					var jsflFile:File = new File(desktop.url + '/temp.jsfl');
					var jsData:String = '';//clearing the previous file data
					for ( var j:uint = 0; j < oneSet.length;j++ )
					{
						var k:uint = oneSet[j];
						var fileURI:String = File((this.searcheFilesModel.getAllFiles())[k]).url;
						jsData += "var fileURI='"+fileURI+"';" + '\n';
						jsData += "fl.publishDocument(fileURI);" + '\n';
					}
					
					var fileName:String = 'batch_' + i.toString() + '.jsfl';
					var batchJSFLCreated:Boolean = this.saveJSFL(fileName, jsData);
					
					if (batchJSFLCreated)
					{
						this.onSavedBatchFile();
					}
					
				}
			}
		}
		
	///////////////////utility methods////////////////////////////////////////////////
		private function saveJSFL(fileNameString:String='default',fileContent:String='nothing',isMasterFile:Boolean=false):Boolean
		{
			var fileName:String = fileNameString;
			var content:String = fileContent;
			
			var masterJSFL:File=new File();
			
			var myPattern:RegExp = / /g;
			var newFileName:String = fileName.replace('.txt','');
			if(newFileName.length > 1){
				var file:File = File.desktopDirectory.resolvePath("buildFiles/" + newFileName.replace(myPattern, '_') + ".jsfl");
				//saving the file preferences
				if (isMasterFile)
				{
					//masterJSFL = file;
					//this.jsflModel.setMasterScriptFile(file);
				}else {
					//this.jsflFiles.push(file);
					this.jsflModel.addScriptFile(file);
				}
				//moving ahead with creation of the file
				var stream:FileStream = new FileStream();
				stream.open(file, FileMode.WRITE);
				var str:String = content;
				//str = str.replace(/\r/g, File.lineEnding);
				stream.writeUTFBytes(str);
				stream.close();
			} else {
				return false;
			}
			return true;
		}
		
		private function onSavedBatchFile():void 
		{
			this.numJSFLCreated++;
			if (this.numJSFLCreated>=this.arrayOfSets.length)
			{
				/*
				this.lblWhichBatch.visible = true;
				this.lblWhichBatch.text += (' '+this.jsflFiles.length);
				this.batchNumTxt.visible = true;
				this.jsflPushBtn.visible = true;
				*/
				//MonsterDebugger.trace(this,'All Batch files are created.');
				//update logger
				var logEvent:LoggerEvent=new LoggerEvent(LoggerEvent.UPDATE_LOG);
				logEvent.setHilightOption(true);
				var msg:String='All Batch Files are created.'+'\n';
				msg+='Total number of batch files = '+this.jsflModel.getScriptFiles().length;
				logEvent.setLogMessage(msg);
				this.dispatch(logEvent);
				//dispatch complete 
				var jcEvent:JSFLCreationEvent=new JSFLCreationEvent(JSFLCreationEvent.COMPLETE_BATCH_CREATION);
				jcEvent.setMainBatchFile(this.jsflModel.getMasterScriptFile());
				jcEvent.setBatchFiles(this.jsflModel.getScriptFiles());
				this.dispatch(jcEvent);
			}else {
				this.createBatchJSFL();
			}
			
		}
		
		
	}
}